import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Button, Space, Modal, Form, Input, InputNumber, message, Popconfirm, Select, Tag, Statistic, Row, Col } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SyncOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';

const { Option } = Select;

const DouyinConfig = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('');
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState(null);

  // 获取抖音配置列表
  const fetchList = async (page = current, size = pageSize) => {
    setLoading(true);
    try {
      const response = await request('/api/v1/douyin', {
        method: 'GET',
        params: {
          page,
          pageSize: size,
        },
      });
      if (response.code === 200) {
        setData(response.data.list);
        setTotal(response.data.total);
      } else {
        message.error(response.msg || '获取抖音配置列表失败');
      }
    } catch (error) {
      message.error('获取抖音配置列表失败');
    }
    setLoading(false);
  };

  // 初始加载
  useEffect(() => {
    fetchList();
  }, []);

  // 批量测试连接
  const handleBatchTest = async () => {
    const hide = message.loading('正在测试连接...', 0);
    try {
      const response = await request('/api/v1/douyin/test-connection', {
        method: 'POST',
      });
      
      if (response.code === 200) {
        message.success('连接测试完成');
        fetchList();
      } else {
        message.error(response.msg || '测试连接失败');
      }
    } catch (error) {
      message.error('测试连接失败');
    } finally {
      hide();
    }
  };

  // 处理表格分页变化
  const handleTableChange = (pagination) => {
    setCurrent(pagination.current);
    setPageSize(pagination.pageSize);
    fetchList(pagination.current, pagination.pageSize);
  };

  // 打开添加/编辑模态框
  const showModal = (record = null) => {
    setEditingId(record ? record.id : null);
    setModalTitle(record ? '编辑抖音配置' : '添加抖音配置');
    form.resetFields();
    if (record) {
      form.setFieldsValue(record);
    }
    setModalVisible(true);
  };

  // 关闭模态框
  const handleCancel = () => {
    setModalVisible(false);
    form.resetFields();
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      const url = editingId ? `/api/v1/douyin/${editingId}` : '/api/v1/douyin';
      const method = editingId ? 'PUT' : 'POST';
      
      const response = await request(url, {
        method,
        data: values,
      });
      
      if (response.code === 200) {
        message.success(editingId ? '更新成功' : '添加成功');
        setModalVisible(false);
        fetchList();
      } else {
        message.error(response.msg || (editingId ? '更新失败' : '添加失败'));
      }
    } catch (error) {
      console.error('表单提交错误:', error);
    }
  };

  // 删除抖音配置
  const handleDelete = async (id) => {
    try {
      const response = await request(`/api/v1/douyin/${id}`, {
        method: 'DELETE',
      });
      
      if (response.code === 200) {
        message.success('删除成功');
        fetchList();
      } else {
        message.error(response.msg || '删除失败');
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 同步抖音配置
  const handleSync = async (id) => {
    try {
      const response = await request(`/api/v1/douyin/${id}/sync`, {
        method: 'POST',
      });
      
      if (response.code === 200) {
        message.success('同步成功');
        fetchList();
      } else {
        message.error(response.msg || '同步失败');
      }
    } catch (error) {
      message.error('同步失败');
    }
  };

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '门店ID',
      dataIndex: 'store_id',
      key: 'store_id',
      width: 100,
    },
    {
      title: '门店名称',
      dataIndex: 'store_name',
      key: 'store_name',
      width: 150,
    },
    {
      title: 'AppKey',
      dataIndex: 'app_key',
      key: 'app_key',
      width: 200,
      ellipsis: true,
    },
    {
      title: 'POI ID',
      dataIndex: 'poi_id',
      key: 'poi_id',
      width: 150,
    },
    {
      title: '同步间隔(分钟)',
      dataIndex: 'sync_interval',
      key: 'sync_interval',
      width: 120,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '最后同步时间',
      dataIndex: 'last_sync_time',
      key: 'last_sync_time',
      width: 180,
      render: (time) => time ? moment(time * 1000).format('YYYY-MM-DD HH:mm:ss') : '-',
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => showModal(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            icon={<SyncOutlined />}
            onClick={() => handleSync(record.id)}
          >
            同步
          </Button>
          <Popconfirm
            title="确定要删除这个配置吗?"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <Card>
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={6}>
            <Statistic title="总配置数" value={total} />
          </Col>
          <Col span={6}>
            <Statistic title="启用配置" value={data.filter(item => item.status === 1).length} valueStyle={{ color: '#3f8600' }} />
          </Col>
          <Col span={6}>
            <Statistic title="禁用配置" value={data.filter(item => item.status === 0).length} valueStyle={{ color: '#cf1322' }} />
          </Col>
          <Col span={6}>
            <Statistic title="最后同步" value={data.length > 0 ? moment(Math.max(...data.map(item => item.last_sync_time || 0)) * 1000).fromNow() : '无'} />
          </Col>
        </Row>

        <div style={{ marginBottom: 16 }}>
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => showModal()}
            >
              添加抖音配置
            </Button>
            <Button
              type="default"
              icon={<CheckCircleOutlined />}
              onClick={handleBatchTest}
            >
              批量测试连接
            </Button>
          </Space>
        </div>
        
        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          pagination={{
            current,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
          }}
          onChange={handleTableChange}
        />
        
        <Modal
          title={modalTitle}
          visible={modalVisible}
          onOk={handleSubmit}
          onCancel={handleCancel}
          width={600}
          destroyOnClose
        >
          <Form
            form={form}
            layout="vertical"
            initialValues={{ status: 1, sync_interval: 30 }}
          >
            <Form.Item
              name="store_id"
              label="门店ID"
              rules={[
                { required: true, message: '请输入门店ID' },
                { type: 'number', min: 1, message: '门店ID必须大于0' }
              ]}
            >
              <InputNumber style={{ width: '100%' }} min={1} />
            </Form.Item>
            
            <Form.Item
              name="store_name"
              label="门店名称"
              rules={[
                { required: true, message: '请输入门店名称' },
                { max: 100, message: '门店名称不能超过100个字符' }
              ]}
            >
              <Input />
            </Form.Item>
            
            <Form.Item
              name="app_key"
              label="AppKey"
              rules={[
                { required: true, message: '请输入AppKey' },
                { max: 100, message: 'AppKey不能超过100个字符' }
              ]}
            >
              <Input />
            </Form.Item>
            
            <Form.Item
              name="app_secret"
              label="AppSecret"
              rules={[
                { required: !editingId, message: '请输入AppSecret' },
                { max: 100, message: 'AppSecret不能超过100个字符' }
              ]}
            >
              <Input.Password 
                placeholder={editingId ? '不修改请留空' : '请输入AppSecret'}
                visibilityToggle={false}
              />
            </Form.Item>
            
            <Form.Item
              name="poi_id"
              label="POI ID"
              rules={[
                { required: true, message: '请输入POI ID' },
                { max: 50, message: 'POI ID不能超过50个字符' }
              ]}
            >
              <Input />
            </Form.Item>
            
            <Form.Item
              name="sync_interval"
              label="同步间隔(分钟)"
              rules={[
                { required: true, message: '请输入同步间隔' },
                { type: 'number', min: 1, message: '同步间隔必须大于0' },
                { type: 'number', max: 1440, message: '同步间隔不能超过24小时' }
              ]}
            >
              <InputNumber style={{ width: '100%' }} min={1} max={1440} />
            </Form.Item>
            
            <Form.Item
              name="status"
              label="状态"
              rules={[{ required: true, message: '请选择状态' }]}
            >
              <Select>
                <Option value={1}>启用</Option>
                <Option value={0}>禁用</Option>
              </Select>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </PageContainer>
  );
};

export default DouyinConfig; 